package com.rainbow.validate.impl

import com.rainbow.validate.ValidateCode
import com.rainbow.validate.ValidateCodeRepository
import com.rainbow.validate.ValidateCodeType
import org.springframework.social.connect.web.HttpSessionSessionStrategy
import org.springframework.stereotype.Component
import org.springframework.web.context.request.ServletWebRequest

/**
 *rainbow
 */
@Component
class SessionValidateCodeRepository : ValidateCodeRepository {

    /**
     * 验证码放入session时的前缀
     */
    val SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_"

    private val sessionStrategy = HttpSessionSessionStrategy()


    override fun save(request: ServletWebRequest, code: ValidateCode, validateCodeType: ValidateCodeType) {
        sessionStrategy.setAttribute(request, getSessionKey(request, validateCodeType), code)
    }

    override fun get(request: ServletWebRequest, validateCodeType: ValidateCodeType): ValidateCode {
        return sessionStrategy.getAttribute(request, getSessionKey(request, validateCodeType)) as ValidateCode
    }

    override fun remove(request: ServletWebRequest, validateCodeType: ValidateCodeType) {
        sessionStrategy.removeAttribute(request, getSessionKey(request, validateCodeType))
    }

    /**
     * 构建验证码
     */
    fun getSessionKey(request: ServletWebRequest, validateCodeType: ValidateCodeType): String {
        return SESSION_KEY_PREFIX + validateCodeType.toString().toLowerCase()
    }
}